const whiteList = [
  "pages/home/index",
  "pages/enterprise/index",
  "pages/private-space/index",
  "pages/user/index",
  "pages/login/index",
  "pages/short-video/index"
]

let isShowModal = false

const routerBeforeEach = (next) => {
  let currentPages = getCurrentPages()
  let currentPage = currentPages[currentPages.length - 1].route
  console.log(currentPages);
  const token = getApp().globalData.token

  // if (whiteList.includes(currentPage) || token) {
  //   // next()
  //   return
  // }

  if (isShowModal) {
    return
  }

  if ( !whiteList.includes(currentPage) && !token) {
    showLoginConfirmModal()
    return
  }
  // next()
}

function showLoginConfirmModal() {
  isShowModal = true
  wx.showModal({
    title: '提示',
    content: '未登录或登录已过期,是否跳转登录界面?',
    success(res) {
      if (res.confirm) {
        console.log('用户点击确定')
        let currentPages = getCurrentPages()
        let params = getParams(currentPages[currentPages.length - 1].options)
        let formUrl = encodeURIComponent(currentPages[currentPages.length - 1].route + `?${params}`)
        console.log(formUrl);
        
        wx.redirectTo({
          url: `/pages/login/index?fromUrl=` + formUrl
        })
      } else if (res.cancel) {
        let route = getCurrentPages()[0].route
        if (route.includes('share')) {
          route = 'pages/home/index'
        }
        wx.switchTab({
          url: '/' + route
        });
      }
      isShowModal = false
    }
  })
}

const OldPage = Page
Page = function (options) {
  const oldLoad = options.onLoad
  const oldShow = options.onShow
  options.onLoad = function (opts) {
    oldLoad.call(this, opts)
    routerBeforeEach(() => {
    })
  }
  // options.onShow = function (opts) {
  //   routerBeforeEach(() => {
  //     oldShow.call(this, opts)
  //     console.log('new onShow')
  //     // 小程序页面 pv 埋点
  //   })
  // }
  OldPage(options)
}

function getParams(params) {
  let paramStr = '';
  Object.keys(params)
    .forEach((item) => {
      if (paramStr === '') {
        paramStr = `${item}=${params[item]}`;
      } else {
        paramStr = `${paramStr}&${item}=${params[item]}`;
      }
    });
  return paramStr
}


